<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">充值套餐设置</div>
          <div class="flex">
            <el-button
              type="primary"
              v-if="role_list[3].has_role"
              @click="
                ;(show_box = true),
                  (price_range_list = []),
                  init_price_range_list(1)
              "
              >新增</el-button
            >

            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          highlight-current-row
          v-loading="loading"
          :default-sort="{ prop: 'name', order: 'descending' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="套餐代号"
            prop="code"
            sortable
            v-if="header_list[0].showTable"
          ></el-table-column>
          <el-table-column
            label="套餐名称"
            prop="name"
            sortable
            v-if="header_list[1].showTable"
            ><template #default="scope: any">
              <div class="text_over" style="width: 100%">
                <el-tooltip :content="scope.row?.name" placement="bottom">
                  {{ scope.row?.name }}
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="套餐申请日期" v-if="header_list[2].showTable">
            <template #default="scope: any" sortable prop="applyTime">
              <div>
                {{ formatDate(parseInt(scope.row?.applyTime), 'yyyy-MM-dd') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="header_list[3].showTable"
            label="申请人"
            sortable
            prop="applyManagerUserName"
          >
          </el-table-column>
          <el-table-column
            v-if="header_list[4].showTable"
            label="套餐启用日期"
            sortable
            prop="enableTime"
          >
            <template #default="scope: any">
              <div>
                {{ formatDate(parseInt(scope.row?.enableTime), 'yyyy-MM-dd') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="header_list[5].showTable"
            label="套餐停用日期"
            sortable
            prop="endTime"
          >
            <template #default="scope: any">
              <div>
                {{ formatDate(parseInt(scope.row?.endTime), 'yyyy-MM-dd') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="header_list[6].showTable"
            label="适用用户类型"
            sortable
            prop="levelIdList"
          >
            <template #default="scope: any">
              <span v-for="(item, index) in enterprise_level_list" :key="index">
                <span
                  style="margin: 0 5px"
                  v-if="scope.row?.levelList?.indexOf(item.name) != -1"
                  >{{ item.name }}
                </span>
              </span>
            </template></el-table-column
          >
          <el-table-column
            v-if="header_list[7].showTable"
            label="套餐介绍"
            sortable
            prop="introduce"
          >
            <template #default="scope: any">
              <div class="text_over" style="width: 100%">
                <el-tooltip :content="scope.row?.introduce" placement="bottom">
                  {{ scope.row?.introduce }}
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="124px">
            <template #default="scope: any">
              <table_edit
                v-if="scope.row?.status == 1"
                :role="role_list"
                @edit_item_status="exam_list(scope)"
                @edit_item="update_list(scope)"
                @delete_item="delete_list(scope)"
              ></table_edit>
              <el-tooltip
                v-if="scope.row?.status != 1 && (role_list[4] as any).has_role"
                content="详情"
                placement="bottom"
              >
                <svgBtn
                  icon="table_info"
                  style="font-size: 20px"
                  @click="exam_list(scope)"
                ></svgBtn>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m_10_0 pagination"
          v-model:currentPage="page_data.current"
          v-model:page-size="page_data.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="
            (e) => {
              page_data.pageSize = e
              get_list()
            }
          "
          @current-change="
            (e) => {
              page_data.current = e
              get_list()
            }
          "
        />
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      @close="resetForm(addrechargepriceform)"
      size="80%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="is_exam">审核</h4>
        <div v-else>
          <h4 v-if="add_page_data.id == ''">新增充值套餐</h4>
          <h4 v-else>编辑充值套餐</h4>
        </div>
      </template>
      <template #default>
        <el-form
          :model="add_page_data"
          label-width="150px"
          :rules="rules"
          ref="addrechargepriceform"
          style="padding-bottom: 80px"
        >
          <div class="form_top">
            <el-form-item label="套餐名称" prop="name">
              <el-input
                placeholder="请输入"
                v-model="add_page_data.name"
                :disabled="is_exam"
                show-word-limit
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="套餐启用日期" prop="enableTime">
              <el-date-picker
                v-model="add_page_data.enableTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="x"
                placeholder="请选择启用日期"
                :disabled="is_exam"
                @change="
                  () => {
                    add_page_data.endTime =
                      add_page_data.enableTime > add_page_data.endTime
                        ? ''
                        : add_page_data.endTime
                  }
                "
              />
            </el-form-item>
            <el-form-item label="套餐停用日期" prop="endTime">
              <el-date-picker
                v-model="add_page_data.endTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="x"
                placeholder="请选择停用日期"
                :disabled="is_exam || add_page_data.enableTime == ''"
                :disabled-date="disabledEnable"
              />
            </el-form-item>
            <el-form-item label="适用用户类型" prop="levelIdList">
              <el-select
                v-model="add_page_data.levelIdList"
                multiple
                :disabled="is_exam"
                @change="select_enterprise_level"
                style="width: 340px"
              >
                <el-option
                  v-for="(item, index) in enterprise_level_list"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="套餐介绍">
            <el-input
              type="textarea"
              rows="4"
              placeholder="请输入"
              v-model="add_page_data.introduce"
              :disabled="is_exam"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <div>
            <el-table
              border
              class="price_table"
              style="text-align: center"
              max-height="300px"
              :data="price_range_list"
            >
              <el-table-column
                label="序号"
                type="index"
                width="80px"
              ></el-table-column>
              <el-table-column label="起始点数">
                <template #default="scope: any">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.startAmount"
                    :disabled="is_exam"
                    @input="
                      scope.row.startAmount = scope.row.startAmount.replace(
                        /^(0+)|[^\d]+/g,
                        ''
                      )
                    "
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="结束点数">
                <template #default="scope: any">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.endAmount"
                    :disabled="is_exam"
                    @input="
                      scope.row.endAmount = scope.row.endAmount.replace(
                        /^(0+)|[^\d]+/g,
                        ''
                      )
                    "
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in table_enterprice_list"
                :key="index"
                :label="item.name"
              >
                <el-table-column label="充值折扣（%）">
                  <template #default="scope: any">
                    <el-input
                      placeholder="请输入"
                      disabled
                      v-model="
                        scope.row.rechargePackageStageLevelList[index].discount
                      "
                      @input="
                        scope.row.rechargePackageStageLevelList[
                          index
                        ].discount = scope.row.rechargePackageStageLevelList[
                          index
                        ].discount.replace(/^(0+)|[^\d]+/g, '')
                      "
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="额外赠送比例（%）">
                  <template #default="scope: any">
                    <el-input
                      placeholder="请输入"
                      disabled
                      v-model="
                        scope.row.rechargePackageStageLevelList[index].give
                      "
                      @input="
                        scope.row.rechargePackageStageLevelList[index].give =
                          scope.row.rechargePackageStageLevelList[
                            index
                          ].give.replace(/^(0+)|[^\d]+/g, '')
                      "
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="备注">
                <template #default="scope: any">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.remark"
                    :disabled="is_exam"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div class="m_top10" v-if="!is_exam">
              <el-button type="primary" @click="init_price_range_list(2)"
                >增加充值设置</el-button
              >
              <el-button @click="reduce_price_range_list"
                >删除最后一行充值设置</el-button
              >
            </div>
          </div>
          <div class="fs_20 fw m_10_0">套餐须知</div>
          <wangeditor
            v-if="!is_exam"
            :text="add_page_data.notice"
            style="height: 500px"
          ></wangeditor>
          <div v-else v-html="add_page_data.notice"></div>
          <div class="box_btn">
            <el-button @click="resetForm(addrechargepriceform)">取消</el-button>
            <el-button
              v-if="!is_exam && add_page_data.status != '2'"
              type="primary"
              :loading="btn_loading"
              @click="submit(addrechargepriceform)"
              >保存</el-button
            >
            <el-button
              v-if="is_exam && add_page_data.status == '1'"
              type="primary"
              :loading="btn_loading"
              @click="exam_submit()"
              >审核</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <dialog_box
      @submit_delete="submit_delete"
      @close="show_delete_box = false"
      :show_delete_box="show_delete_box"
      :delete_name="delete_name"
    ></dialog_box>
  </div>
</template>

<script lang="ts" setup>
import { check_role, formatDate, handle_search_key } from '@/utils/utils' // 权限校验
import wangeditor from '@/view/components/wangeditor.vue'
import search from '@/view/components/search.vue'
import dialog_box from '@/view/components/dialog_box.vue'
import table_edit from '@/view/components/table_edit.vue'
import svgBtn from '@/components/svg_button.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, reactive, nextTick, computed } from 'vue'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import store from '@/store'
// type FormInstance = InstanceType<typeof ElForm>
const addrechargepriceform = ref<FormInstance>()
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入代号', trigger: 'blur' }],
  enableTime: [{ required: true, message: '请选择启用日期', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择停用日期', trigger: 'blur' }],
  levelIdList: [
    {
      required: true,
      type: 'array',
      message: '请选择适用用户类型',
      trigger: 'change',
    },
  ],
})
const role_list = ref([
  { path: 'rechargePrice/pass', has_role: false },
  { path: 'rechargePrice/edit', has_role: false },
  { path: 'rechargePrice/delete', has_role: false },
  { path: 'rechargePrice/post', has_role: false },
  { path: 'rechargePrice/info', has_role: false },
])
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
})
const list = ref()
const total = ref()
const loading = ref(false)
const show_box = ref(false)

const disabledEnable = (time) => {
  return time.getTime() < add_page_data.value.enableTime
}
const enterprise_level_list = ref()
const height_size = ref(1)
const header_list = ref([
  {
    label: '套餐代号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '套餐名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '套餐申请日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '申请人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '套餐启用日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '套餐停用日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '适用用户类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: computed(() => {
      return enterprise_level_list.value
    }),
  },
  {
    label: '套餐介绍',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 10,
  applyTime: '',
  levelList: '',
  applicant: '',
  code: '',
  enableTime: '',
  endTime: '',
  introduce: '',
  name: '',
})
const add_page_data = ref({
  id: '',
  applicant: store.state.user_info.id,
  applyManagerUsername: store.state.user_info.name,
  applyTime: Date.now(),
  enableTime: '',
  code: '',
  introduce: '',
  name: '',
  endTime: '',
  rechargePackageStageList: [],
  status: '',
  levelIdList: [],
  notice: '',
})
const price_range_list = ref([])
onMounted(() => {
  EventBus.on('refresh', () => {
    get_list()
    get_enterprise_level_list()
    ElMessage.success('刷新成功！')
  })
  EventBus.on('get_text', (e) => {
    console.log(e)
  })
  EventBus.on('commit_editor', (e) => {
    // 获取富文本编译器 内容
    console.log(e)
    to_submit(e)
  })
  get_list()
  get_enterprise_level_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('get_text')
  EventBus.off('commit_editor')
})

const table_enterprice_list = ref([])
const select_enterprise_level = (e) => {
  console.log(e)
  table_enterprice_list.value = []
  price_range_list.value = []
  for (let i in enterprise_level_list.value) {
    if (e.indexOf(enterprise_level_list.value[i].id) != -1) {
      table_enterprice_list.value.push(enterprise_level_list.value[i])
    }
  }
  console.log(table_enterprice_list.value)
  init_price_range_list(1)
}
const exam_submit = () => {
  ElMessageBox.confirm('确定审核通过该充值套餐？', '提示', {
    confirmButtonText: '确定',
    closeOnClickModal: false,
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.rechargePackage_pass + '/' + add_page_data.value.id,
          method: 'put',
        })
        .then((res) => {
          ElMessage.success('审核成功！')
          setTimeout(() => {
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    })
    .catch(() => {})
}
const to_submit = (e) => {
  let is_complete = 1 // 判断参数 合理
  price_range_list.value.forEach((item, index) => {
    if (item.endAmount == '' || item.startAmount == '') {
      is_complete = 2
    }
    if (parseInt(item.endAmount) <= parseInt(item.startAmount)) {
      is_complete = 3
    }
    if (
      index > 0 &&
      parseInt(item.startAmount) <=
        parseInt(price_range_list.value[index - 1].endAmount)
    ) {
      is_complete = 4
    }
    item.rechargePackageStageLevelList.forEach((element, index1) => {
      element.discount = element.discount == '' ? '100' : element.discount
      element.give = element.give == '' ? '0' : element.give
      if (add_page_data.value.levelIdList.indexOf(element.levelId) == -1) {
        item.rechargePackageStageLevelList.splice(index1, 1)
      }
    })
  })
  if (is_complete == 2) {
    ElMessage.error('请完善套餐的起始以及结束点数')
    btn_loading.value = false
    return
  } else if (is_complete == 3) {
    ElMessage.error('所有充值设置的结束点数必须大于起始点数')
    btn_loading.value = false
    return
  } else if (is_complete == 4) {
    ElMessage.error('所有充值设置的起始点数必须大于上一条设置结束点数')
    btn_loading.value = false
    return
  }
  let submit_data = JSON.parse(JSON.stringify(add_page_data.value))
  submit_data.notice = e
  //   submit_data.endTime = Date.parse(submit_data.endTime) as any
  //   submit_data.enableTime = Date.parse(submit_data.enableTime) as any
  submit_data.rechargePackageStageList = price_range_list.value
  axios
    .request({
      url:
        submit_data.id == ''
          ? serviceApi.rechargePackage_curd
          : serviceApi.rechargePackage_curd + '/' + submit_data.id,
      method: submit_data.id == '' ? 'post' : 'put',
      data: submit_data,
    })
    .then((res) => {
      ElMessage.success('操作成功！')
      setTimeout(() => {
        btn_loading.value = false
        show_box.value = false
        resetForm(addrechargepriceform.value)
        get_list()
      }, 1000)
    })
    .catch((error) => {
      btn_loading.value = false
      ElMessage.error(error)
    })
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    console.log(valid)
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      EventBus.emit('submit')
    }
  })
}
const get_current_item = (e) => {
  add_page_data.value.levelIdList = []
  enterprise_level_list.value.forEach((item) => {
    if (e.levelList.includes(item.name)) {
      add_page_data.value.levelIdList.push(item.id)
    }
  })
  axios
    .request({
      url: serviceApi.rechargePackage_curd + '/' + e.id,
      method: 'get',
    })
    .then((res) => {
      console.log(res)
      add_page_data.value = {
        id: res.data.id,
        applyTime: res.data.applyTime,
        applicant: res.data.applyManagerUser.id,
        applyManagerUsername: res.data.applyManagerUser.id,
        enableTime: formatDate(parseInt(res.data.enableTime), 'yyyy-MM-dd'),
        endTime: formatDate(parseInt(res.data.endTime), 'yyyy-MM-dd'),
        code: res.data.code,
        introduce: res.data.introduce,
        name: res.data.name,
        rechargePackageStageList: [],
        status: res.data.status,
        levelIdList: add_page_data.value.levelIdList,
        notice: res.data.notice,
      }
      console.log(add_page_data.value)
      price_range_list.value = res.data.rechargePackageStageList
      table_enterprice_list.value = []
      for (let i in enterprise_level_list.value) {
        if (
          add_page_data.value.levelIdList.indexOf(
            enterprise_level_list.value[i].id
          ) != -1
        ) {
          table_enterprice_list.value.push(enterprise_level_list.value[i])
        }
      }
      show_box.value = true
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const is_exam = ref(false)
const exam_list = (e) => {
  is_exam.value = true
  get_current_item(e.row)
}
const update_list = (e) => {
  is_exam.value = false
  get_current_item(e.row)
}
const show_delete_box = ref(false)
const delete_name = ref()
const delete_list = (e) => {
  add_page_data.value.id = e.row.id
  delete_name.value = e.row.code
  show_delete_box.value = true
}
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.rechargePackage_curd + '/' + add_page_data.value.id,
      method: 'delete',
    })
    .then((res) => {
      ElMessage.success('删除成功！')
      setTimeout(() => {
        show_delete_box.value = false
        get_list()
      }, 1000)
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const init_price_range_list = (e) => {
  if (
    e == 2 &&
    price_range_list.value[price_range_list.value.length - 1].endAmount == ''
  ) {
    ElMessage.warning('请完善已有记录的充值点数设置')
    return
  }
  var a = {
    rechargePackageStageLevelList: [],
    endAmount: '',
    startAmount: '',
    remark: '',
  }
  setTimeout(() => {
    for (let i in table_enterprice_list.value) {
      var b = {
        discount: '',
        give: '',
        levelId: table_enterprice_list.value[i].id,
      }
      a.rechargePackageStageLevelList.push(b)
    }
    price_range_list.value.push(a)
    console.log(price_range_list.value)
  }, 100)
}
const reduce_price_range_list = () => {
  if (price_range_list.value.length > 1) {
    price_range_list.value.splice(price_range_list.value.length - 1, 1)
  } else {
    ElMessage.warning('至少保留一行充值设置！')
  }
}
const get_enterprise_level_list = () => {
  axios
    .request({
      url: serviceApi.enterprise_level_list,
      method: 'post',
    })
    .then((res) => {
      res.data.forEach((item) => {
        item.label = item.name
        item.value = item.name
      })
      enterprise_level_list.value = res.data
      price_range_list.value = []
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const get_list = () => {
  axios
    .request({
      url: serviceApi.rechargePackage_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    code: header_list.value[0].value,
    name: header_list.value[1].value,
    applicant: header_list.value[3].value,
    applyTime: header_list.value[2].value as any,
    enableTime: header_list.value[4].value as any,
    endTime: header_list.value[5].value as any,
    levelList: header_list.value[6].value as any,
    introduce: header_list.value[7].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_page_data.value = {
    id: '',
    applicant: store.state.user_info.id,
    applyManagerUsername: store.state.user_info.id,
    applyTime: Date.now(),
    enableTime: '',
    code: '',
    introduce: '',
    name: '',
    endTime: '',
    rechargePackageStageList: [],
    status: '',
    levelIdList: [],
    notice: '',
  }
  table_enterprice_list.value = []
  is_exam.value = false
  show_box.value = false
}
</script>

<style lang="scss" scoped>
// :deep(.el-select .el-input__inner) {
//   height: 32px !important;
// }
.price_table {
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
.box_btn {
  background-color: #fff;
  position: absolute;
  width: calc(100% - 20px);
  bottom: 0;
  right: 20px;
  padding: 20px 0;
  text-align: right;
}
.form_top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .el-form-item {
    width: 50%;
  }
}
</style>
